<script setup lang="ts">
import {Modal} from "ant-design-vue";
import {
  PlusOutlined,
} from "@ant-design/icons-vue";
import {computed, ref, unref} from "vue";
import JPage from "../page";
import JTable from "../table";
import JForm, {JQueryForm} from "../form";
import JCrudToolbar from "./crud-toolbar.vue";
import {JCrudProps} from "./crud";

// function sleep(ms) {
//   return new Promise(resolve => setTimeout(resolve, ms));
// }

defineOptions({
  name: "JCrud",
})
const props = defineProps<JCrudProps>()
const emits = defineEmits(['query', 'create', 'update', 'delete']);

const columns = props.table.columns
const filterColumns = ref(columns)
const formColumns = columns.filter(it => it.type !== undefined)

const tableSize = ref<string>("large");
const saveModel = ref<Record<string, any>>({})
const queryModel = ref<Record<string, any>>({})
const formColNum = ref<number>(2);
const saveModelWidth = computed(() => {
  return (formColNum.value * 400) + 'px'
})

const showModal = ref(false);
const modalTitle = ref<string>("")
const isCreate = ref(false);
const loading = ref(false);
const saving = ref(false);
const deleting = ref(false);

async function onQuery() {
  console.debug('[j-crud] - onQuery,', queryModel.value)
  loading.value = true
  try {
    emits('query', queryModel.value)
    // await sleep(3000)
  } finally {
    loading.value = false
  }
}

function onSave() {
  console.debug('[j-crud] - onSave,', saveModel.value)
  saving.value = true
  try {
    if (isCreate.value) {
      console.debug('[j-crud] - create,', saveModel.value)
      emits('create', saveModel.value)
    } else {
      console.debug('[j-crud] - update,', saveModel.value)
      emits('update', saveModel.value)
    }
  } finally {
    saving.value = false
  }
  showModal.value = false
  Modal.destroyAll()
  onQuery()
}

function onDelete(row: Record<string, any>) {
  const _row = {...row}
  console.debug('[j-crud] - onDelete,', row)
  deleting.value = true
  try {
    emits('delete', _row)
  } finally {
    deleting.value = false
  }
  onQuery()
}

function showCreate() {
  modalTitle.value = '新增' + props.name
  isCreate.value = true;
  showModal.value = true
  saveModel.value = {}
}

function showUpdate(row: Record<string, any>) {
  modalTitle.value = '编辑' + props.name
  const _row = {...row}
  console.debug('[j-crud] - showUpdate,', row)
  isCreate.value = false;
  showModal.value = true
  saveModel.value = _row
}
</script>

<template>
  <j-page>
    <a-card style="margin-bottom: 16px">
      <JQueryForm :items="formColumns" :loading="loading" :model="queryModel" @query="onQuery"></JQueryForm>
    </a-card>

    <a-card :title="props.name+'列表'">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="showCreate">
            <template #icon>
              <PlusOutlined/>
            </template>
            新增
          </a-button>
          <JCrudToolbar :columns="columns"
                        :loading="loading"
                        @refresh="onQuery"
                        @change-size="it => tableSize = it"
                        @change-columns="it => filterColumns = it"/>
        </a-space>
      </template>
      <j-table
          v-bind="props.table"
          :columns="filterColumns"
          :size="tableSize"
      >
        <template #bodyCell="{ column, record}">
          <template v-if="column?.dataIndex === 'action'">
            <a-space>
              <a-button type="link" :size="'small'">详情</a-button>
              <a-button type="link" :size="'small'" @click="showUpdate(record)">编辑</a-button>
              <a-popconfirm
                  title="确定删除该条数据？" ok-text="确定" cancel-text="取消"
                  @confirm="onDelete(record)"
              >
                <a-button type="link" :size="'small'" danger :loading="deleting">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </j-table>
    </a-card>

    <a-modal v-model:open="showModal" :title="modalTitle"
             :style="{'min-width': '300px','width': saveModelWidth}" ok-text="保存"
             :okButtonProps="{loading: saving}"
             @ok="onSave">
      <j-form :items="formColumns" :model="saveModel" :col-num="formColNum"></j-form>
    </a-modal>
  </j-page>
</template>
